package com.example.demo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.demo.entity.Book;
import com.example.demo.service.BookService;
import jakarta.annotation.Resource;
import org.springframework.boot.Banner;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class BookController {

    @Resource
    private BookService bookService;


    @GetMapping("/books")
    public String findAllBooks(Model model){
        List<Book> books = bookService.findAllBook();
        model.addAttribute("books",books);
        return "/bookList";
    }

    @RequestMapping("/searchBooks")
    public String searchBooks(Book book,Model model){
        List<Book> books = bookService.searchBooks(book);
        model.addAttribute("books",books);
        model.addAttribute("b",book);
        return "/bookList";
    }

    @GetMapping("/booksPage")
    public String booksPage(@RequestParam(value="pageNum", defaultValue="1") int pageNum,
                            @RequestParam(value="pageSize", defaultValue="5") int pageSize,
                            Model model, @ModelAttribute Book book) {
        IPage bookPage = bookService.getPage(pageNum, pageSize, book);
        model.addAttribute("books", bookPage);
        model.addAttribute("b", book);
        return "/bookList";
    }

    @RequestMapping("/add")
    public String addTiao(){
        return "addBook";
    }

    @RequestMapping("/addBooks")
    public String addBooks(Book book){
        bookService.addBook(book);
        return "redirect:/searchBooks";
    }

    @RequestMapping("/deleteBooks")
    public String deleteStudent(@RequestParam("id") int id){
        bookService.deleteBook(id);
        return "redirect:/searchBooks";
    }

    @GetMapping("/updateBook/{id}")
    public String toUpdateStudent(@PathVariable("id") int id,Model model){
        Book book=bookService.findBookById(id);
        model.addAttribute("book",book);
        return "/updateBook";
    }

    @PostMapping("/updateBook")
    public String UpdateStudent(Book book,Model model){
        bookService.updateBook(book);
        model.addAttribute("redirect:/books");
        return "redirect:/searchBooks";
    }
}
